const {
    stockMonitorUrls,
    pushTask,
} = require('./ti_config');

const {
    wxpusher,
} = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    httpGet,
    httpPost,
    sleep,
} = require('./util');

process.on('unhandledRejection', error => {
    //...不处理...
});

let openSerials = [];//需要关注的规格

//每N秒重新拉取任务列表
(async () => {
    while (1) {
        const tasks = await readTask();
        if (!tasks) continue;
        const tmpOpenSerials = [];
        for (const task of tasks) {
            if (task.status != 1) continue;
            tmpOpenSerials.push(task.serial);
        }
        openSerials = tmpOpenSerials;

        await sleep(30000);
    }
})();

//可能有虚假库存（商品有库存，但具体的规格缺货），这里记录下来，避免不断重复扫描
let noInventoryStockNum = {};

//清理缓存
(async () => {
    while (1) {
        await sleep(3600000);
        noInventoryStockNum = {};
    }
})();

const referer = 'https://www.ti.com.cn/zh-cn/power-management/overview.html';

//循环拉取库存信息
(async () => {
    while (1) {
        for (const stockMonitorUrl of stockMonitorUrls) {
            try {
                logger(`请求 ${stockMonitorUrl}`);
                const ret = JSON.parse(await httpGet(stockMonitorUrl, referer));
                for (const v of ret.ParametricResults) {
                    if (!v.p3318 || v.p3318 == '0') continue;
                    for (const serial of openSerials) {
                        let parentSerial = v.o1.split('-')[0];
                        //特殊处理
                        if (parentSerial == 'TLV758P') parentSerial = 'TLV758';
                        if (parentSerial == 'TLV733P') parentSerial = 'TLV733';
                        if (serial.indexOf(parentSerial) < 0) continue;
                        const key = serial + '_' + v.o1;
                        if (noInventoryStockNum[key] && noInventoryStockNum[key] == v.p3318) continue;
                        logger('显示有库存，需检查具体规格', serial, v.o1, v.p3318);

                        //检查是不是真的有库存
                        const fullUrl = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn='+encodeURIComponent(serial);
                        const res = JSON.parse(await httpGet(fullUrl, referer));
                        const stock = res.inventory;
                        if (stock > 0) {
                            const msg = `规格 ${serial} 检测到有 ${stock} 库存可以下单`;
                            logger(msg);

                            try {
                                //推送消息
                                await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
                                    appToken: wxpusher.appToken,
                                    content: msg,
                                    contentType: 1,
                                    uids: wxpusher.uids,
                                }), 'application/json');
                            } catch(e) {
                                logger(e);
                            }

                            //推送规格到服务器
                            await httpPost(pushTask, 'serial='+serial);
                            await sleep(60000);
                        } else {
                            logger(`${serial} 无库存`);
                        }

                        noInventoryStockNum[key] = v.p3318;
                    }
                }
            } catch(e) {
                logger('拉取库存失败，稍后重试', e);
                await sleep(10000);
                continue;
            }

            await sleep(2000);
        }
    }
})();

